/* 
 * File:   FieldSolver.cpp
 * Author: Lucky
 * 
 * Created on 5. říjen 2011, 11:06
 */

#include<iostream>

#include "FieldSolver.h"
#include "Chessboard.h"
#include "Field.h"
#include "Library.h"
#include "Result.h"

FieldSolver::FieldSolver(int width, int height, int q, int* coords, Field* field) {
    m_width = width;
    m_height = height;
    m_q = q;
    m_coords = coords;
    m_field = field;
    m_board = new Chessboard(m_width, m_height, m_coords, m_q);
    m_res = 0; //0 je NULL
}

FieldSolver::FieldSolver(const FieldSolver& orig) {
}

FieldSolver::~FieldSolver() {
    delete m_field;
}

void FieldSolver::compute() {
    int counter = 0;
    
    do {
        ++counter;
        
        if (m_board->getOnLightsCount() == 0) {
            std::cout << "Mam lepsi vysledek!" << std::endl;
            int* coords = new int[2*m_field->getSwitchCount()];
            std::cout<<"SC"<<m_field->getSwitchCount()<<std::endl;
            int j = 0;
            for (int i = 0; i < m_field->m_length; i++) {
                
                if (m_field->m_field[i]) {
                    std::cout << Library::getXCoord(m_width, i) << "X" << Library::getYCoord(m_width, i) << std::endl;
                    coords[j++] = Library::getXCoord(m_width, i);
                    coords[j++] = Library::getYCoord(m_width, i);
                }
            }
            if (m_res != 0) {
                delete m_res;
            }
            m_res = new Result(m_field->getSwitchCount(), coords);
        }
    } while (increaseField());
    
    std::cout << counter << std::endl;
    if (m_res != 0) {
        m_res->printCoords();
    } else {
        std::cout << "Nenalezeno reseni" << std::endl;
    }
}

bool FieldSolver::increaseField() {
    int fieldLength = m_field->m_length;
    int point = fieldLength - 1; //posledni polozka fieldu
    while (point > m_field->m_end && point >= 0) {
        if (m_field->m_field[point] == false) {
            if (m_res != 0 && m_field->getSwitchCount() >= m_res->getSteps() - 1) {
                --point;
                continue;
            }
            m_field->setState(point, true); //m_field->m_field[point] = true;
            m_board->pressLight(Library::getXCoord(m_width, point), Library::getYCoord(m_width, point));
            for (int i = point+1; i < fieldLength; i++) {
                if (m_field->m_field[i]) {
                    m_board->pressLight(Library::getXCoord(m_width, i), Library::getYCoord(m_width, i));
                }
                m_field->setState(i, false);//m_field->m_field[i] = false;
            }
            return true;
        } else {
            --point;
        }
    }
    
    return false;
}


